package com.ericsson.enap.modules.monitor.service.impl;

import com.ericsson.enap.modules.topology.entity.CabMonitorServerEntity;
import com.ericsson.enap.modules.topology.entity.CabServer;
import com.ericsson.enap.modules.sys.entity.EpcDict;
import com.ericsson.enap.modules.monitor.mapper.CabMonitorMapper;
import com.ericsson.enap.modules.monitor.mapper.CabServerMapper;
import com.ericsson.enap.modules.sys.mapper.EpcDictMapper;
import com.ericsson.enap.modules.monitor.service.CabMonitorService;
import com.ericsson.common.util.DateUtils;
import com.ericsson.common.util.LogFileName;
import com.ericsson.common.util.LoggerUtils;
import com.mongodb.BasicDBObject;
import com.mongodb.client.model.IndexModel;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务器状态获取（CPU，内存等
 * ）
 */
@Service("server")
public class CabMonitorServerServiceImpl implements CabMonitorService {
    private static String COMMAND_CEE1="chphss -cee CEE1";
    private static String COMMAND_CEE5="chphss -cee CEE5";
    private static String COMMAND_CEE6="chphss -cee CEE6";
    private static String COMMAND_CEE16="chphss -cee CEE16";

//      private static String COMMAND_CEE1="cat /opt/cee1.txt";
//      private static String COMMAND_CEE5="cat /opt/cee5.txt";
//
//    private static String COMMAND_CEE1="cmd.exe /c type D:\\cee1.txt";
//    private static String COMMAND_CEE5="cmd.exe /c type D:\\cee5.txt";
    private Logger log = LoggerUtils.Logger(LogFileName.CabMonitorServerJob);
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private CabMonitorMapper cabMonitorMapper;
    @Autowired
    private EpcDictMapper epcDictMapper;
    @Autowired
    private CabServerMapper cabServerMapper;
    private static String CAB_MONGO_TIME="CAB_MONGO_TIME";
    @Override
    public void dealEquipStatus() {
        String epcDate=DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:00");
        List<CabMonitorServerEntity> cabMonitorServerEntityCEE5List=this.readServerStatus_CEE1(epcDate);
        List<CabMonitorServerEntity> cabMonitorServerEntityCEE1List=this.readServerStatus_CEE5(epcDate);
        List<CabMonitorServerEntity> cabMonitorServerEntityCEE6List=this.readServerStatus_CEE6(epcDate);
        List<CabMonitorServerEntity> cabMonitorServerEntityCEE16List=this.readServerStatus_CEE16(epcDate);
        log.info("CabMonitorServerServiceImpl insert into mongodb end");
        log.info("CabMonitorServerServiceImpl update mysql start");
        cabMonitorServerEntityCEE5List.addAll(cabMonitorServerEntityCEE1List);
        cabMonitorServerEntityCEE5List.addAll(cabMonitorServerEntityCEE6List);
        cabMonitorServerEntityCEE5List.addAll(cabMonitorServerEntityCEE16List);
        cabMonitorMapper.updateServerCliLoginName(cabMonitorServerEntityCEE5List);
        log.info("CabMonitorServerServiceImpl update mysql end");
        log.info("CabMonitorServerServiceImpl update server role start");
        this.updateServerRole(cabMonitorServerEntityCEE5List);
        log.info("CabMonitorServerServiceImpl update server role end");
        EpcDict epcDict=new EpcDict();
        epcDict.setKeyName(CAB_MONGO_TIME);
        epcDict= epcDictMapper.selectEpcDict(epcDict);
        if(null!=epcDict&&!"".equals(epcDict.getKeyValue())) {
            this.dropPastCollection(Integer.parseInt(epcDict.getKeyValue()));
        }
    }

    /**
     * 读取接入方式为CEE5的服务器状态
     */
    private List<CabMonitorServerEntity> readServerStatus_CEE5(String epcDate){
        List<CabMonitorServerEntity> cabMonitorServerEntityCEE5List=readStatus(COMMAND_CEE5,epcDate);
        this.bathInsertMongo(cabMonitorServerEntityCEE5List, DateUtils.dateTime());
        return cabMonitorServerEntityCEE5List;
    }

    /**
     * 读取接入方式为CEE1的服务器状态
     */
    private List<CabMonitorServerEntity> readServerStatus_CEE1(String epcDate){
        List<CabMonitorServerEntity> cabMonitorServerEntityCEE1List=readStatus(COMMAND_CEE1,epcDate);
        this.bathInsertMongo(cabMonitorServerEntityCEE1List, DateUtils.dateTime());
        return cabMonitorServerEntityCEE1List;
    }

    /**
     * 读取接入方式为CEE6的服务器状态
     */
    private List<CabMonitorServerEntity> readServerStatus_CEE6(String epcDate){
        List<CabMonitorServerEntity> cabMonitorServerEntityCEE6List=readStatus(COMMAND_CEE6,epcDate);
        this.bathInsertMongo(cabMonitorServerEntityCEE6List, DateUtils.dateTime());
        return cabMonitorServerEntityCEE6List;
    }

    /**
     * 读取接入方式为CEE16的服务器状态
     */
    private List<CabMonitorServerEntity> readServerStatus_CEE16(String epcDate){
        List<CabMonitorServerEntity> cabMonitorServerEntityCEE16List=readStatus(COMMAND_CEE16,epcDate);
        this.bathInsertMongo(cabMonitorServerEntityCEE16List, DateUtils.dateTime());
        return cabMonitorServerEntityCEE16List;
    }

    private List<CabMonitorServerEntity> readStatus(String command,String epcDate) {
        List<CabMonitorServerEntity> cabMonitorServerEntityList=new ArrayList<>();
        Process proc = null;
        BufferedReader br;
        String line;
        try {
            long start = System.currentTimeMillis();
            proc = Runtime.getRuntime().exec(command);
            br = new BufferedReader(new InputStreamReader(proc.getInputStream()), 10 * 1024 * 1024);
            int remark=0;
            while ((line = br.readLine()) != null) {
                //第一行为头，丢弃
                if (remark!=0) {
                    List<String> resultStringList = getSplitList(line);
                    //if(resultStringList.size()==42&&null!=resultStringList.get(6)&&!"".equals(resultStringList.get(6))){
                    if(null!=resultStringList.get(6)&&!"".equals(resultStringList.get(6))){
                        CabMonitorServerEntity cabMonitorServerEntity=readListData(resultStringList);
                        cabMonitorServerEntity.setEpcTimestamp(epcDate);
                        cabMonitorServerEntityList.add(cabMonitorServerEntity);
                    }
                }
                remark++;
            }
            long end = System.currentTimeMillis();
            log.info(command+"execute time is: " + (end - start) + "ms");
        } catch (IOException e) {
            log.error("readStatus"+e.getMessage());
        } finally {
            proc.destroy();
        }
        return cabMonitorServerEntityList;
    }

    public CabMonitorServerEntity readListData(List<String> resultStringList){
        CabMonitorServerEntity cabMonitorServerEntity=new CabMonitorServerEntity();
        Map<String,String> ethMap=new HashMap<String,String>();
        if(!StringUtils.isEmpty(resultStringList.get(0))) {
            cabMonitorServerEntity.setIp(resultStringList.get(0));
        }
        if(!StringUtils.isEmpty(resultStringList.get(1))) {
            cabMonitorServerEntity.setMac(resultStringList.get(1));
        }
        if(!StringUtils.isEmpty(resultStringList.get(2))) {
            cabMonitorServerEntity.setStatus(resultStringList.get(2));
        }
        if(!StringUtils.isEmpty(resultStringList.get(3))) {
            cabMonitorServerEntity.setName(resultStringList.get(3));
        }
        if(!StringUtils.isEmpty(resultStringList.get(4))) {
            cabMonitorServerEntity.setRoles(resultStringList.get(4));
        }
        if(!StringUtils.isEmpty(resultStringList.get(5))) {
            cabMonitorServerEntity.setTimestamp(resultStringList.get(5));
        }
        cabMonitorServerEntity.setSerialNumber(resultStringList.get(6));
        if(!StringUtils.isEmpty(resultStringList.get(7))) {
            cabMonitorServerEntity.setCpuUsage(resultStringList.get(7));
        }
        if(!StringUtils.isEmpty(resultStringList.get(8))) {
            cabMonitorServerEntity.setMemUsage(resultStringList.get(8));
        }
        if(!StringUtils.isEmpty(resultStringList.get(9))) {
            cabMonitorServerEntity.setFileUsage(resultStringList.get(9));
        }
        int m=10;
        for(int i=0;i<=15;i++) {
            if (!StringUtils.isEmpty(resultStringList.get(m)) && !"".equals(resultStringList.get(m))) {
                ethMap.put("eth"+i+"R", resultStringList.get(m));
            }
            m=m+1;
            if (!StringUtils.isEmpty(resultStringList.get(m)) && !"".equals(resultStringList.get(m))) {
                ethMap.put("eth"+i+"T", resultStringList.get(m));
            }
            m=m+1;
        }

        int n=42;
        for(int j=0;j<2;j++) {
            if (!StringUtils.isEmpty(resultStringList.get(n)) && !"".equals(resultStringList.get(n))) {
                ethMap.put("control"+j+"R", resultStringList.get(n));
            }
            n=n+1;
            if (!StringUtils.isEmpty(resultStringList.get(n)) && !"".equals(resultStringList.get(n))) {
                ethMap.put("control"+j+"T", resultStringList.get(n));
            }
            n=n+1;
        }

        int x=46;
        for(int y=0;y<2;y++) {
            if (!StringUtils.isEmpty(resultStringList.get(x)) && !"".equals(resultStringList.get(x))) {
                ethMap.put("storage"+y+"R", resultStringList.get(x));
            }
            x=x+1;
            if (!StringUtils.isEmpty(resultStringList.get(x)) && !"".equals(resultStringList.get(x))) {
                ethMap.put("storage"+y+"T", resultStringList.get(x));
            }
            x=x+1;
        }
        cabMonitorServerEntity.setEthMap(ethMap);
        return cabMonitorServerEntity;
    }

    private void bathInsertMongo(List<CabMonitorServerEntity> cabMonitorServerEntityList,String date){
        if(!mongoTemplate.collectionExists("cab_monitor_"+date+"_server")) {
            List<IndexModel> indexModelList = new ArrayList<>();
            BasicDBObject index = new BasicDBObject();
            index.put("serialNumber", 1);
            index.put("epcTimestamp", 1);
            indexModelList.add(new IndexModel(index));
            mongoTemplate.createCollection("cab_monitor_"+date+"_server").createIndexes(indexModelList);
        }
        mongoTemplate.insert(cabMonitorServerEntityList,"cab_monitor_"+date+"_server");
    }

    public ArrayList<String> getSplitList(String str) {
        ArrayList<String> list = new ArrayList<String>();
        int index = 0;
        int len = str.length();
        StringBuilder temp = new StringBuilder();
        char c;
        while (true) {
            c = str.charAt(index);
            if (c == ',') {
                list.add(temp.toString());
                temp.setLength(0);
            } else if (c == '\"') {
                while (true) {
                    index++;
                    c = str.charAt(index);
                    if (c == '\"' || index == len - 1) {
                        break;
                    }
                    temp.append(c);
                }
            } else {
                temp.append(c);
            }
            if (index == len - 1) {
                list.add(temp.toString());
                break;
            }
            index++;
        }
        return  list;
    }

    /**
     * 删除过期的集合
     * @param pastDay
     */
    public void dropPastCollection(int pastDay){
        String pastDate=DateUtils.getPastDate(pastDay,"yyyyMMdd");
        if(mongoTemplate.collectionExists("cab_monitor_"+pastDate+"_server")) {
            log.info("drop past collection start "+"cab_monitor_"+pastDate+"_server");
            mongoTemplate.dropCollection("cab_monitor_"+pastDate+"_server");
            log.info("drop past collection end "+"cab_monitor_"+pastDate+"_server");
        }
    }

    /**
     * 更新Server的Role
     * @param cabMonitorServerEntities
     */
    private void updateServerRole(List<CabMonitorServerEntity> cabMonitorServerEntities){
        List<CabServer> resultList=new ArrayList<>();
        CabServer cabServer;
        List<CabServer> cabServerList=cabServerMapper.selectCabServer();
        Map<String,String> cabServerMap=cabServerList.stream().collect(Collectors.toMap(CabServer::getSerialNo,CabServer::getRole, (key1, key2) -> key2));

        for(CabMonitorServerEntity cabMonitorServerEntity:cabMonitorServerEntities){
            if(cabServerMap.containsKey(cabMonitorServerEntity.getSerialNumber())){
                cabServer =new CabServer();
                cabServer.setSerialNo(cabMonitorServerEntity.getSerialNumber());
                String role=cabServerMap.get(cabMonitorServerEntity.getSerialNumber());
                if(role.contains("(")){
                    role.replaceAll("\\([^)]*\\)",cabMonitorServerEntity.getRoles());
                    cabServer.setRole(role);
                }else{
                    cabServer.setRole(role+"("+cabMonitorServerEntity.getRoles()+")");
                }
                resultList.add(cabServer);
            }
        }
        cabServerMapper.updateServerRole(resultList);
    }
}
